package com.jing.weibo.controller.system;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import weibo4j.model.WeiboException;

import com.jing.system.comm.BaseController;
import com.jing.system.comm.contants.WeiboCons;
import com.jing.weibo.pojo.user.UserInfo;
import com.jing.weibo.service.system.StatisticsService;

/**
 * 统计的Controller
 * @author jing.yue
 * @version 2012/09/11 1.0.0
 */
@Controller
public class StatisticsController extends BaseController {

	private static final Logger logger = Logger.getLogger(StatisticsController.class);

	@Autowired
	private StatisticsService statisticsService;

	/**
	 * 跳转到统计页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/toStatisticsManager")
	public String toStatisticsManager(HttpServletRequest request, ModelMap modelMap) {
		UserInfo userInfo = getSessionUser(request);
		//不为管理员
		if(userInfo.getIsadmin().intValue() != 1) {
			logger.error(userInfo.getNickname() + ": 您不是管理员!");
			return ERROR_ADMIN;
		}
		try {
			//获取总用户数
			Integer countUser = statisticsService.findCountUser();
			modelMap.put("countUser", countUser);

			//获取今日活跃用户数
			Integer countActiveUser = statisticsService.findCountActiveUser();
			modelMap.put("countActiveUser", countActiveUser);

			//获取今日新增用户数
			Integer countAddUser = statisticsService.findCountAddUser();
			modelMap.put("countAddUser", countAddUser);

		} catch (Exception e) {
			logger.error("获取信息异常!", e);
			return ERROR_ADMIN;
		}
		return "admin/statistics/statistics_manager";
	}

	/**
	 * 分页获取最近登录的用户列表
	 * @return
	 */
	@RequestMapping(value = "/statistics/json/findlatelyLoginUser")
	@ResponseBody
	public ModelMap findlatelyLoginUser(HttpServletRequest request, UserInfo user) {
		String result = null;
		String weiboMsg = null;
		Map<String, Object> map = null;
		UserInfo userInfo = getSessionUser(request);
		//不为管理员
		if(userInfo.getIsadmin().intValue() != 1) {
			logger.error(userInfo.getNickname() + ": 您不是管理员!");
			result = ERROR;
		}
		else {
			try {
				user.setUsername(userInfo.getUsername());
				map = statisticsService.findlatelyLoginUser(user);
				result = SUCCESS;
			} catch (WeiboException e) {
				logger.error(WeiboCons.getErrorMsg(e));
				result = ERROR_WEIBO;
				weiboMsg = WeiboCons.getErrorMsg(e);
			} catch (Exception e) {
				logger.error(userInfo.getNickname() + ": 获取最近登录的用户列表异常!", e);
				result = ERROR;
			}
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("data", map);
		modelMap.put("result", result);
		modelMap.put("weiboMsg", weiboMsg);
		return modelMap;
	}

}